 <template>
  <view class="map-page" @click="handlePageClick">
    <!-- 导航栏组件 -->
    <navbar-component title="地图定位" @goBack="goBack" />

    <!-- 搜索框 -->
    <view class="search-container" @click.stop>
      <view class="search-box">
        <input
          id="tipinput"
          class="search-input"
          placeholder="请输入地址进行搜索"
          v-model="searchKeyword"
          @input="onSearchInput"
          @focus="onSearchFocus"
          @blur="onSearchBlur"
          @click="onSearchClick"
        />
        <view class="search-icon">🔍</view>
      </view>

      <!-- 搜索结果列表 -->
      <view
        v-if="showSearchResults && searchResults.length > 0"
        class="search-results"
      >
        <view
          v-for="(item, index) in searchResults"
          :key="index"
          class="result-item"
          @click="selectLocation(item, true)"
        >
          <view class="result-title">{{ item.name }}</view>
          <view class="result-address">{{ getDisplayAddress(item) }}</view>
        </view>
      </view>

      <!-- 搜索历史下拉框 -->
      <view v-if="showSearchHistory" class="search-history" @click.stop>
        <view class="history-header">
          <text class="history-title">搜索历史</text>
          <text
            v-if="searchHistory.length > 0"
            class="clear-all-btn"
            @click="clearAllHistory"
            >清空</text
          >
        </view>
        <scroll-view
          v-if="searchHistory.length > 0"
          class="history-list"
          scroll-y="true"
        >
          <view
            v-for="(item, index) in searchHistory"
            :key="index"
            class="history-item"
            @click="selectHistoryItem(item.keyword)"
          >
            <view class="history-content">
              <text class="history-icon">🔍</text>
              <text class="history-text">{{ item.keyword }}</text>
            </view>
            <view class="history-meta">
              <text class="history-time">{{ item.time }}</text>
              <text class="delete-btn" @click.stop="deleteHistoryItem(index)"
                >×</text
              >
            </view>
          </view>
        </scroll-view>
        <view v-else class="empty-history">
          <text class="empty-icon">📝</text>
          <text class="empty-text">暂无搜索历史</text>
        </view>
      </view>
    </view>

    <!-- 地图内容区域 -->
    <view id="container"></view>

    <!-- 错误提示页面 -->
    <view
      v-if="showError"
      class="error-container"
      @click="handleErrorPageClick"
    >
      <view class="error-content">
        <view class="error-icon">⚠️</view>
        <view class="error-title">连接服务器超时</view>
        <view class="error-message">点击屏幕重试</view>
        <button class="retry-btn" @click="retryLoad">重新加载</button>
      </view>
    </view>

    <!-- 选中的位置信息 - 带动画效果 -->
    <view
      v-if="selectedLocation"
      class="location-info"
      :class="{ 'location-info--expanded': showLocationInfo }"
      @click="toggleLocationInfo"
      @click.stop
    >
      <!-- 收起状态显示 -->
      <view v-if="!showLocationInfo" class="location-info-collapsed">
        <view class="location-title-collapsed">{{
          selectedLocation.name
        }}</view>
        <view class="expand-icon">▲</view>
      </view>

      <!-- 展开状态显示 -->
      <view v-if="showLocationInfo" class="location-info-expanded">
        <view class="location-header">
          <view class="location-title">{{ selectedLocation.name }}</view>
          <view class="collapse-icon" @click.stop="toggleLocationInfo">▼</view>
        </view>
        <view class="location-address">{{ selectedLocation.address }}</view>
        <button class="confirm-btn" @click="confirmLocation">确认位置</button>
      </view>
    </view>
  </view>
</template>

<script>
import NavbarComponent from "../../zujian/navbar.vue";
import { ref, onMounted, onUnmounted } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";

export default {
  name: "MapPage",
  components: {
    NavbarComponent,
  },
  setup() {
    // 响应式数据
    const map = ref(null);
    const searchKeyword = ref("");
    const searchResults = ref([]);
    const showSearchResults = ref(false);
    const selectedLocation = ref(null);
    const autoComplete = ref(null);
    const placeSearch = ref(null);
    const currentMarker = ref(null);
    const showLocationInfo = ref(false); // 新增：控制位置信息面板的展开/收起
    const autoHideTimer = ref(null); // 新增：自动隐藏定时器
    const showError = ref(false); // 新增：控制错误页面显示
    const searchHistory = ref([]); // 新增：搜索历史
    const showSearchHistory = ref(false); // 新增：控制搜索历史显示

    // 初始化地图
    const initMap = () => {
      console.log("开始初始化地图...");

      try {
        window._AMapSecurityConfig = {
          securityJsCode: "f2c115e02fdfda640fb2d62d09d69bbb",
        };

        console.log("高德地图安全配置已设置");

        // 设置加载超时
        const loadTimeout = setTimeout(() => {
          console.error("地图加载超时");
          showError.value = true;
        }, 15000); // 15秒超时

        AMapLoader.load({
          key: "d6f54354bfb0f55f3c6fbd794dfa502f",
          version: "2.0",
          plugins: [
            "AMap.Scale",
            "AMap.AutoComplete",
            "AMap.PlaceSearch",
            "AMap.Geolocation",
            "AMap.Geocoder",
            "AMap.Marker"
          ],
          AMapUI: {
            version: "1.1",
          },
        })
          .then((AMap) => {
            // 清除超时定时器
            clearTimeout(loadTimeout);

            // 将AMap保存到window对象，供其他函数使用
            window.AMap = AMap;

            // 创建地图实例
            map.value = new AMap.Map("container", {
              viewMode: "2D",
              cacheEnable: true, // 开启本地缓存
              zoom: 13,
              center: [116.397428, 39.90923],
              tileRetry: 3,
              resizeEnable: true,
              // 设置地图预加载级别
              preload: 2, // 预加载范围设置为2
              // 其他预加载相关配置
              preloadMode: "adjacent", // 预加载相邻区域
              preloadModeRadius: 2000, // 预加载半径，单位：像素
              preloadModeZoom: 3, // 预加载的缩放级别范围
              showIndoorMap: false, // 关闭室内地图以提升性能
              showBuildingBlock: false, // 关闭建筑物块以提升性能
              // features: ['bg', 'road', 'building'], // 只加载必要的图层
            });

            // 初始化自动完成插件
            try {
              if (AMap.Autocomplete) {
                autoComplete.value = new AMap.Autocomplete({
                  input: "tipinput",
                  city: "全国",
                });
                console.log("自动完成插件初始化成功");
              } else {
                console.warn("AMap.Autocomplete 插件未加载");
              }
            } catch (error) {
              console.warn("自动完成插件初始化失败:", error);
            }

            // 初始化地点搜索插件
            try {
              if (AMap.PlaceSearch) {
                placeSearch.value = new AMap.PlaceSearch({
                  map: map.value,
                  pageSize: 10,
                  pageIndex: 1,
                  city: "全国", // 设置搜索范围为全国
                  extensions: "all", // 返回详细信息
                  type: "", // 不限制POI类型，包含所有类型
                  citylimit: false, // 不限制城市范围
                });
                console.log("地点搜索插件初始化成功");
              } else {
                console.warn("AMap.PlaceSearch 插件未加载");
              }
            } catch (error) {
              console.warn("地点搜索插件初始化失败:", error);
            }

            // 监听自动完成选择事件
            if (autoComplete.value) {
              autoComplete.value.on("select", (e) => {
                const poi = e.poi;
                if (poi) {
                  console.log("自动完成选择的POI:", poi);
                  // 构建完整的地址信息
                  let fullAddress = "";

                  // 如果有省份信息，添加到地址中
                  if (poi.province && poi.province !== poi.city) {
                    fullAddress += poi.province;
                  }

                  // 如果有城市信息，添加到地址中
                  if (poi.city && poi.city !== poi.district) {
                    fullAddress += poi.city;
                  }

                  // 如果有区域信息，添加到地址中
                  if (poi.district) {
                    fullAddress += poi.district;
                  }

                  // 如果有详细地址，添加到地址中
                  if (poi.address) {
                    fullAddress += poi.address;
                  }

                  searchResults.value = [
                    {
                      name: poi.name || "未知地点",
                      address: poi.address || "",
                      district: poi.district || "",
                      province: poi.province || "",
                      city: poi.city || "",
                      fullAddress: fullAddress || "地址信息暂无",
                      location: poi.location,
                    },
                  ];
                  showSearchResults.value = true;
                  selectLocation(searchResults.value[0], true);
                }
              });
            }

            // 监听地图点击事件
            map.value.on("click", (e) => {
              const lnglat = e.lnglat;
              // 根据坐标获取地址信息
              getAddressFromLocation(lnglat);

              // 地图点击时隐藏搜索相关内容
              hideSearchHistory();

              // 让搜索框失去焦点
              const searchInput = document.getElementById("tipinput");
              if (searchInput) {
                searchInput.blur();
              }
            });

            // 初始化定位控件
            initGeolocation();
          })
          .catch((e) => {
            // 清除超时定时器
            clearTimeout(loadTimeout);
            console.error("地图加载失败:", e);
            showError.value = true;
          });
      } catch (error) {
        console.error("地图初始化错误:", error);
        uni.showToast({
          title: "地图初始化失败",
          icon: "none",
        });
      }
    };

    // 搜索输入处理
    const onSearchInput = (e) => {
      searchKeyword.value = e.detail.value;
      if (searchKeyword.value.trim()) {
        performSearch();
        showSearchHistory.value = false; // 有搜索内容时隐藏历史
      } else {
        searchResults.value = [];
        showSearchResults.value = false;
        showSearchHistory.value = true; // 搜索框为空时显示历史
      }
    };

    // 执行搜索
    const performSearch = () => {
      if (!placeSearch.value || !searchKeyword.value.trim()) return;

      placeSearch.value.search(searchKeyword.value, (status, result) => {
        console.log("搜索结果:", status, result);
        if (status === "complete" && result.poiList) {
          // 使用Promise.all来并行获取详细地址信息
          const promises = result.poiList.pois.map(async (poi) => {
            console.log("POI详情:", poi);
            try {
              const detailedInfo = await getDetailedAddress(poi);
              return detailedInfo;
            } catch (error) {
              console.error("获取详细地址失败:", error);
              // 如果获取详细地址失败，使用基本信息
              let fullAddress = "";
              if (poi.province && poi.province !== poi.city) {
                fullAddress += poi.province;
              }
              if (poi.city && poi.city !== poi.district) {
                fullAddress += poi.city;
              }
              if (poi.district) {
                fullAddress += poi.district;
              }
              if (poi.address) {
                fullAddress += poi.address;
              }

              return {
                name: poi.name || "未知地点",
                address: poi.address || "",
                district: poi.district || "",
                province: poi.province || "",
                city: poi.city || "",
                fullAddress: fullAddress || "地址信息暂无",
                location: poi.location,
              };
            }
          });

          Promise.all(promises)
            .then((results) => {
              searchResults.value = results;
              showSearchResults.value = true;
            })
            .catch((error) => {
              console.error("处理搜索结果失败:", error);
              searchResults.value = [];
              showSearchResults.value = false;
            });
        } else {
          searchResults.value = [];
          showSearchResults.value = false;
        }
      });
    };

    // 选择位置
    const selectLocation = (location, isFromSearch = false) => {
      selectedLocation.value = location;
      showSearchResults.value = false;
      showLocationInfo.value = true; // 选择位置时自动展开面板

      // 只有从搜索结果选择时才添加到搜索历史
      if (isFromSearch) {
        addToHistory(location.name);
      }

      // 清除之前的定时器
      if (autoHideTimer.value) {
        clearTimeout(autoHideTimer.value);
        autoHideTimer.value = null;
      }

      // 设置自动收起定时器（5秒后自动收起）
      autoHideTimer.value = setTimeout(() => {
        showLocationInfo.value = false;
        autoHideTimer.value = null;
      }, 5000);

      try {
        // 清除之前的标记
        if (currentMarker.value) {
          map.value.remove(currentMarker.value);
        }

        // 添加新标记
        if (window.AMap && window.AMap.Marker) {
          currentMarker.value = new window.AMap.Marker({
            position: location.location,
            map: map.value,
          });
        } else {
          console.warn("AMap.Marker 插件未加载");
        }

        // 移动地图到选中位置
        map.value.setCenter(location.location);
        map.value.setZoom(15);
      } catch (error) {
        console.error("选择位置错误:", error);
        // 即使标记创建失败，也要更新位置信息
        map.value.setCenter(location.location);
        map.value.setZoom(15);
      }
    };

    // 根据坐标获取地址
    const getAddressFromLocation = (lnglat) => {
      try {
        if (!window.AMap || !window.AMap.Geocoder) {
          console.warn("AMap.Geocoder 插件未加载");
          // 使用默认位置信息
          const location = {
            name: "未知位置",
            address: `经度: ${lnglat.lng}, 纬度: ${lnglat.lat}`,
            district: "未知区域",
            location: lnglat,
          };
          selectLocation(location);
          return;
        }

        const geocoder = new window.AMap.Geocoder({
          radius: 1000,
          extensions: "all",
        });

        geocoder.getAddress(lnglat, (status, result) => {
          console.log("地理编码结果:", status, result);
          console.log("详细地址组件:", result?.regeocode?.addressComponent);
          console.log("POI信息:", result?.regeocode?.pois);
          console.log("格式化地址:", result?.regeocode?.formattedAddress);

          if (status === "complete" && result.regeocode) {
            const addressComponent = result.regeocode.addressComponent;
            const formattedAddress = result.regeocode.formattedAddress;
            const pois = result.regeocode.pois || [];

            // 尝试获取更准确的位置名称
            let locationName = "未知位置";

            // 优先使用POI名称（兴趣点）
            if (pois.length > 0 && pois[0].name) {
              locationName = pois[0].name;
            }
            // 其次使用建筑物名称
            else if (
              addressComponent.building &&
              addressComponent.building !== ""
            ) {
              locationName = addressComponent.building;
            }
            // 再次使用小区名称
            else if (
              addressComponent.neighborhood &&
              addressComponent.neighborhood !== ""
            ) {
              locationName = addressComponent.neighborhood;
            }
            // 再次使用街道名称
            else if (
              addressComponent.street &&
              addressComponent.street !== ""
            ) {
              locationName = addressComponent.street;
            }
            // 最后使用道路名称
            else if (addressComponent.road && addressComponent.road !== "") {
              locationName = addressComponent.road;
            }
            // 如果都没有，使用格式化地址的前几个字符
            else if (formattedAddress) {
              const addressParts = formattedAddress.split("号");
              if (addressParts.length > 1) {
                locationName = addressParts[0] + "号";
              } else {
                locationName = formattedAddress.substring(0, 20);
              }
            }

            const location = {
              name: locationName,
              address:
                formattedAddress || `经度: ${lnglat.lng}, 纬度: ${lnglat.lat}`,
              district: addressComponent.district || "未知区域",
              location: lnglat,
            };

            console.log("解析后的位置信息:", location);
            selectLocation(location);
          } else {
            console.warn("地理编码失败:", status, result);
            // 使用默认位置信息
            const location = {
              name: "未知位置",
              address: `经度: ${lnglat.lng}, 纬度: ${lnglat.lat}`,
              district: "未知区域",
              location: lnglat,
            };
            selectLocation(location);
          }
        });
      } catch (error) {
        console.error("地理编码错误:", error);
        // 使用默认位置信息
        const location = {
          name: "未知位置",
          address: `经度: ${lnglat.lng}, 纬度: ${lnglat.lat}`,
          district: "未知区域",
          location: lnglat,
        };
        selectLocation(location);
      }
    };

    // 初始化定位控件
    const initGeolocation = () => {
      if (!map.value) {
        console.warn("地图未初始化");
        return;
      }

      try {
        if (!window.AMap || !window.AMap.Geolocation) {
          console.warn("AMap.Geolocation 插件未加载");
          return;
        }

        const geolocation = new window.AMap.Geolocation({
          enableHighAccuracy: true,
          timeout: 8000, // 减少超时时间到8秒
          maximumAge: 30000, // 减少缓存时间到30秒，提高定位频率
          convert: true,
          showButton: true,
          showMarker: true,
          showCircle: true,
          panToLocation: true,
          zoomToAccuracy: true,
          buttonPosition: "RB",
          buttonOffset: new window.AMap.Pixel(10, 20),
          GeoLocationFirst: true,
          useNative: true, // 优先使用原生定位
        });

        map.value.addControl(geolocation);

        // 监听定位成功事件
        geolocation.on("complete", (result) => {
          console.log("定位成功:", result);
          try {
            const lnglat = result.position;
            if (lnglat) {
              getAddressFromLocation(lnglat);
            } else {
              console.warn("定位结果中没有位置信息");
            }
          } catch (error) {
            console.error("处理定位结果时出错:", error);
          }
        });

        // 监听定位失败事件
        geolocation.on("error", (error) => {
          console.warn("定位失败:", error);
          // 显示用户友好的错误提示
          uni.showToast({
            title: "定位失败，请检查定位权限",
            icon: "none",
            duration: 2000,
          });
        });

        // 立即开始定位，不等待延迟
        console.log("立即开始自动定位...");
        try {
          geolocation.getCurrentPosition((status, result) => {
            console.log("自动定位结果:", status, result);
            try {
              if (status === "complete" && result && result.position) {
                const lnglat = result.position;
                getAddressFromLocation(lnglat);
              } else {
                console.warn("初始定位失败:", status, result);
                // 如果立即定位失败，延迟500ms后重试一次
                setTimeout(() => {
                  console.log("重试定位...");
                  geolocation.getCurrentPosition((retryStatus, retryResult) => {
                    if (
                      retryStatus === "complete" &&
                      retryResult &&
                      retryResult.position
                    ) {
                      getAddressFromLocation(retryResult.position);
                    }
                  });
                }, 500);
              }
            } catch (error) {
              console.error("处理自动定位结果时出错:", error);
            }
          });
        } catch (error) {
          console.error("执行自动定位时出错:", error);
        }
      } catch (error) {
        console.error("定位控件初始化错误:", error);
      }
    };

    // 确认位置
    const confirmLocation = () => {
      if (selectedLocation.value) {
        const locationName = selectedLocation.value.name;

        // 判断是否为学校或学院
        const isSchool = checkIfSchool(locationName);
        console.log("位置名称:", locationName, "是否为学校:", isSchool);

        if (isSchool) {
          console.log("✅ 检测到学校位置，允许确认选择");
        } else {
          console.log("❌ 非学校位置，显示业务提示");
        }

        if (isSchool) {
          // 如果是学校，显示确认对话框
          uni.showModal({
            title: "确认位置",
            content: `是否确认选择：${locationName}`,
            success: (res) => {
              if (res.confirm) {
                console.log("选中的位置:", selectedLocation.value);

                // 传递位置信息到main页面
                console.log("检测到学校位置，准备传递数据");

                // 使用全局数据存储，确保数据能正确传递
                const app = getApp();
                app.globalData = app.globalData || {};
                app.globalData.selectedSchoolName = locationName;
                console.log("已将学校名称存储到全局数据:", locationName);

                uni.showToast({
                  title: "学校位置已确认",
                  icon: "success",
                });

                // 返回上一页
                uni.navigateBack({
                  delta: 1,
                });
              }
            },
          });
        } else {
          // 如果不是学校，显示提示信息并提供选项
          uni.showModal({
            title: "位置提示",
            content: `"${locationName}" 不是学校或学院，没有涉及到校园帮业务。\n\n请选择附近的学校或学院，如：\n• 大学\n• 学院\n• 学校\n• 高校`,
            showCancel: true,
            cancelText: "继续搜索",
            confirmText: "知道了",
            success: (res) => {
              if (res.confirm) {
                // 用户点击"知道了"，不做任何操作
                console.log("用户确认了提示信息");
              } else if (res.cancel) {
                // 用户点击"继续搜索"，清空搜索框并聚焦
                console.log("用户选择继续搜索");
                searchKeyword.value = "";
                // 延迟聚焦搜索框
                setTimeout(() => {
                  const searchInput = document.getElementById("tipinput");
                  if (searchInput) {
                    searchInput.focus();
                  }
                }, 100);
              }
            },
          });
        }
      }
    };

    // 判断是否为学校或学院
    const checkIfSchool = (name) => {
      if (!name) return false;

      // 主要学校关键词
      const primaryKeywords = ["大学", "学院", "学校", "高校", "院校"];

      // 专业类型关键词（需要配合主要关键词使用）
      const specialtyKeywords = [
        "师范",
        "理工",
        "科技",
        "工业",
        "农业",
        "医科",
        "中医",
        "药科",
        "财经",
        "政法",
        "外语",
        "艺术",
        "体育",
        "音乐",
        "美术",
        "舞蹈",
        "戏剧",
        "传媒",
        "新闻",
        "出版",
        "印刷",
        "轻工",
        "纺织",
        "建筑",
        "交通",
        "水利",
        "电力",
        "石油",
        "化工",
        "冶金",
        "地质",
        "矿业",
        "林业",
        "海洋",
        "水产",
        "畜牧",
        "兽医",
        "园艺",
        "园林",
        "农学",
        "生物",
        "环境",
        "生态",
        "气象",
        "地震",
        "测绘",
        "天文",
        "地理",
        "历史",
        "哲学",
        "文学",
        "语言",
        "教育",
        "心理",
        "社会",
        "政治",
        "经济",
        "管理",
        "法律",
        "国际",
        "外交",
        "军事",
        "公安",
        "消防",
        "武警",
        "国防",
        "航天",
        "航空",
        "航海",
        "船舶",
        "轮机",
      ];

      // 检查是否包含主要学校关键词
      const hasPrimaryKeyword = primaryKeywords.some((keyword) =>
        name.includes(keyword)
      );

      // 如果包含主要关键词，直接认为是学校
      if (hasPrimaryKeyword) {
        console.log(
          "检测到主要学校关键词:",
          primaryKeywords.find((keyword) => name.includes(keyword))
        );
        return true;
      }

      // 如果包含专业关键词，进一步判断
      const hasSpecialtyKeyword = specialtyKeywords.some((keyword) =>
        name.includes(keyword)
      );

      // 如果包含专业关键词且名称长度适中（避免误判），认为是学校
      if (hasSpecialtyKeyword && name.length >= 4 && name.length <= 20) {
        console.log(
          "检测到专业关键词:",
          specialtyKeywords.find((keyword) => name.includes(keyword))
        );
        return true;
      }

      console.log("未检测到学校关键词");
      return false;
    };

    // 测试学校判断逻辑（开发时使用）
    // const testSchoolDetection = () => {
    //   const testCases = [
    //     '清华大学',
    //     '北京大学',
    //     '河北大学',
    //     '保定理工学院',
    //     '中央美术学院',
    //     '北京理工大学',
    //     '中国政法大学',
    //     '北京外国语大学',
    //     '北京体育大学',
    //     '北京电影学院',
    //     '星巴克咖啡',
    //     '肯德基',
    //     '万达广场',
    //     '医院',
    //     '银行'
    //   ];

    //   console.log('=== 学校判断测试 ===');
    //   testCases.forEach(name => {
    //     const isSchool = checkIfSchool(name);
    //     console.log(`${name}: ${isSchool ? '是学校' : '不是学校'}`);
    //   });
    //   console.log('=== 测试结束 ===');
    // };

    // 在开发环境下运行测试
    // if (process.env.NODE_ENV === 'development') {
    //   setTimeout(() => {
    //     testSchoolDetection();
    //   }, 3000);
    // }

    // 搜索框点击事件
    const onSearchClick = (event) => {
      // 阻止事件冒泡，避免触发全局点击事件
      event.stopPropagation();

      if (searchKeyword.value.trim() === "") {
        showSearchHistory.value = true;
        showSearchResults.value = false;
      }
    };

    // 搜索框焦点事件
    const onSearchFocus = () => {
      if (searchResults.value.length > 0) {
        showSearchResults.value = true;
        showSearchHistory.value = false;
      } else if (searchKeyword.value.trim() === "") {
        // 搜索框为空时显示历史记录
        showSearchHistory.value = true;
      }
    };

    const onSearchBlur = () => {
      // 延迟隐藏搜索结果和历史记录，避免点击事件冲突
      setTimeout(() => {
        showSearchResults.value = false;
        showSearchHistory.value = false;
      }, 150); // 减少延迟时间，让响应更快
    };

    // 添加搜索历史
    const addToHistory = (keyword) => {
      if (!keyword || !keyword.trim()) return;

      const trimmedKeyword = keyword.trim();
      const now = new Date();
      const timeString = `${now.getHours().toString().padStart(2, "0")}:${now
        .getMinutes()
        .toString()
        .padStart(2, "0")}`;

      // 创建历史记录对象
      const historyItem = {
        keyword: trimmedKeyword,
        time: timeString,
        timestamp: now.getTime(),
      };

      // 移除已存在的相同关键词
      const index = searchHistory.value.findIndex(
        (item) => item.keyword === trimmedKeyword
      );
      if (index > -1) {
        searchHistory.value.splice(index, 1);
      }

      // 添加到开头
      searchHistory.value.unshift(historyItem);

      // 限制历史记录数量（最多保存20条）
      if (searchHistory.value.length > 20) {
        searchHistory.value = searchHistory.value.slice(0, 20);
      }

      // 保存到本地存储
      saveHistoryToStorage();
    };

    // 删除单条历史记录
    const deleteHistoryItem = (index) => {
      searchHistory.value.splice(index, 1);
      saveHistoryToStorage();
    };

    // 清空所有历史记录
    const clearAllHistory = () => {
      uni.showModal({
        title: "确认清空",
        content: "确定要清空所有搜索历史吗？",
        success: (res) => {
          if (res.confirm) {
            searchHistory.value = [];
            saveHistoryToStorage();
            showSearchHistory.value = false;
            uni.showToast({
              title: "已清空历史记录",
              icon: "success",
            });
          }
        },
      });
    };

    // 选择历史记录项
    const selectHistoryItem = (keyword) => {
      searchKeyword.value = keyword;
      showSearchHistory.value = false;

      // 直接搜索并选择第一个结果
      if (placeSearch.value) {
        placeSearch.value.search(keyword, (status, result) => {
          if (
            status === "complete" &&
            result.poiList &&
            result.poiList.pois.length > 0
          ) {
            const firstResult = result.poiList.pois[0];
            console.log("历史记录搜索结果:", firstResult);
            // 构建完整的地址信息
            let fullAddress = "";

            // 如果有省份信息，添加到地址中
            if (
              firstResult.province &&
              firstResult.province !== firstResult.city
            ) {
              fullAddress += firstResult.province;
            }

            // 如果有城市信息，添加到地址中
            if (firstResult.city && firstResult.city !== firstResult.district) {
              fullAddress += firstResult.city;
            }

            // 如果有区域信息，添加到地址中
            if (firstResult.district) {
              fullAddress += firstResult.district;
            }

            // 如果有详细地址，添加到地址中
            if (firstResult.address) {
              fullAddress += firstResult.address;
            }

            const location = {
              name: firstResult.name || "未知地点",
              address: firstResult.address || "",
              district: firstResult.district || "",
              province: firstResult.province || "",
              city: firstResult.city || "",
              fullAddress: fullAddress || "地址信息暂无",
              location: firstResult.location,
            };
            selectLocation(location, true);
          }
        });
      }
    };

    // 保存历史记录到本地存储
    const saveHistoryToStorage = () => {
      try {
        // 确保数据是有效的数组格式
        if (Array.isArray(searchHistory.value)) {
          const historyData = JSON.stringify(searchHistory.value);
          // 验证JSON字符串是否有效
          JSON.parse(historyData); // 测试解析
          uni.setStorageSync("searchHistory", historyData);
        } else {
          console.warn("搜索历史数据格式无效，重置为空数组");
          searchHistory.value = [];
          uni.setStorageSync("searchHistory", "[]");
        }
      } catch (error) {
        console.error("保存搜索历史失败:", error);
        // 如果保存失败，清除可能损坏的数据
        try {
          uni.removeStorageSync("searchHistory");
        } catch (removeError) {
          console.error("清除存储失败:", removeError);
        }
      }
    };

    // 从本地存储加载历史记录
    const loadHistoryFromStorage = () => {
      try {
        const history = uni.getStorageSync("searchHistory");
        if (history) {
          // 检查是否为有效的JSON字符串
          if (typeof history === "string" && history.trim().startsWith("[")) {
            searchHistory.value = JSON.parse(history);
          } else {
            // 如果不是有效的JSON，清除存储并重置
            console.warn("检测到无效的搜索历史数据，已清除");
            uni.removeStorageSync("searchHistory");
            searchHistory.value = [];
          }
        } else {
          searchHistory.value = [];
        }
      } catch (error) {
        console.error("加载搜索历史失败:", error);
        // 清除损坏的数据
        try {
          uni.removeStorageSync("searchHistory");
          console.log("已清除损坏的搜索历史数据");
        } catch (removeError) {
          console.error("清除存储失败:", removeError);
        }
        searchHistory.value = [];
      }
    };

    // 隐藏搜索历史
    const hideSearchHistory = () => {
      showSearchHistory.value = false;
      showSearchResults.value = false;
    };

    // 页面点击事件处理
    const handlePageClick = (event) => {
      // 检查点击的元素是否在搜索相关区域内
      const target = event.target;

      // 兼容性处理：检查closest方法是否存在
      if (target && typeof target.closest === "function") {
        // 如果点击的是搜索框、搜索结果或搜索历史，不隐藏
        if (
          target.closest(".search-container") ||
          target.closest(".search-history") ||
          target.closest(".search-results")
        ) {
          return;
        }
      } else {
        // 如果closest方法不存在，使用兼容性方案
        let element = target;
        while (element && element !== document.body) {
          if (
            element.className &&
            (element.className.includes("search-container") ||
              element.className.includes("search-history") ||
              element.className.includes("search-results"))
          ) {
            return;
          }
          element = element.parentElement;
        }
      }

      // 否则隐藏搜索历史并让搜索框失去焦点
      hideSearchHistory();

      // 让搜索框失去焦点
      const searchInput = document.getElementById("tipinput");
      if (searchInput) {
        searchInput.blur();
      }
    };

    // 切换位置信息面板的展开/收起
    const toggleLocationInfo = () => {
      showLocationInfo.value = !showLocationInfo.value;

      // 清除之前的定时器
      if (autoHideTimer.value) {
        clearTimeout(autoHideTimer.value);
        autoHideTimer.value = null;
      }

      // 如果展开，设置自动收起定时器（5秒后自动收起）
      if (showLocationInfo.value) {
        autoHideTimer.value = setTimeout(() => {
          showLocationInfo.value = false;
          autoHideTimer.value = null;
        }, 5000);
      }

      // 隐藏搜索相关内容
      hideSearchHistory();

      // 让搜索框失去焦点
      const searchInput = document.getElementById("tipinput");
      if (searchInput) {
        searchInput.blur();
      }
    };

    // 返回上一页
    const goBack = () => {
      uni.navigateBack();
    };

    // 重试加载地图
    const retryLoad = () => {
      console.log("重试加载地图");
      showError.value = false;
      initMap();
    };

    // 错误页面点击事件处理
    const handleErrorPageClick = (event) => {
      // 如果点击的是重试按钮，不处理
      const target = event.target;
      if (target && typeof target.closest === "function") {
        if (target.closest(".retry-btn")) {
          return;
        }
      } else {
        // 兼容性处理
        let element = target;
        while (element && element !== document.body) {
          if (element.className && element.className.includes("retry-btn")) {
            return;
          }
          element = element.parentElement;
        }
      }

      // 隐藏搜索相关内容
      hideSearchHistory();

      // 让搜索框失去焦点
      const searchInput = document.getElementById("tipinput");
      if (searchInput) {
        searchInput.blur();
      }
    };

    // 生命周期
    onMounted(() => {
      console.log("地图页面已挂载");

      // 加载搜索历史
      loadHistoryFromStorage();

      // 检查网络连接
      uni.getNetworkType({
        success: (res) => {
          console.log("网络类型:", res.networkType);
          if (res.networkType === "none") {
            uni.showToast({
              title: "请检查网络连接",
              icon: "none",
            });
            return;
          }
          initMap();
        },
        fail: () => {
          console.warn("无法获取网络状态，继续初始化地图");
          initMap();
        },
      });
    });

    onUnmounted(() => {
      if (map.value) {
        map.value.destroy();
      }

      // 清理定时器
      if (autoHideTimer.value) {
        clearTimeout(autoHideTimer.value);
        autoHideTimer.value = null;
      }
    });

    // 获取详细地址信息的函数
    const getDetailedAddress = (poi) => {
      return new Promise((resolve) => {
        if (!poi.location || !window.AMap || !window.AMap.Geocoder) {
          console.warn("AMap.Geocoder 插件未加载或位置信息缺失");
          resolve({
            name: poi.name || "未知地点",
            address: poi.address || "",
            district: poi.district || "",
            province: poi.province || "",
            city: poi.city || "",
            fullAddress: "",
            location: poi.location,
          });
          return;
        }

                try {
          const geocoder = new window.AMap.Geocoder({
            radius: 1000,
            extensions: "all",
          });

          geocoder.getAddress(poi.location, (status, result) => {
            if (status === "complete" && result.regeocode) {
              const addressComponent = result.regeocode.addressComponent;
              const formattedAddress = result.regeocode.formattedAddress;

              // 构建完整的地址信息
              let fullAddress = "";

              // 添加省份信息
              if (addressComponent.province) {
                fullAddress += addressComponent.province;
              }

              // 添加城市信息
              if (addressComponent.city) {
                fullAddress += addressComponent.city;
              }

              // 添加区域信息
              if (addressComponent.district) {
                fullAddress += addressComponent.district;
              }

              // 添加详细地址
              if (formattedAddress) {
                fullAddress += formattedAddress;
              }

              resolve({
                name: poi.name || "未知地点",
                address: poi.address || addressComponent.street || "",
                district: poi.district || addressComponent.district || "",
                province: poi.province || addressComponent.province || "",
                city: poi.city || addressComponent.city || "",
                fullAddress: fullAddress || "地址信息暂无",
                location: poi.location,
              });
            } else {
              resolve({
                name: poi.name || "未知地点",
                address: poi.address || "",
                district: poi.district || "",
                province: poi.province || "",
                city: poi.city || "",
                fullAddress: "",
                location: poi.location,
              });
            }
          });
        } catch (error) {
          console.error("地理编码器创建失败:", error);
          resolve({
            name: poi.name || "未知地点",
            address: poi.address || "",
            district: poi.district || "",
            province: poi.province || "",
            city: poi.city || "",
            fullAddress: "",
            location: poi.location,
          });
        }
      });
    };

    // 获取显示地址的辅助函数
    const getDisplayAddress = (item) => {
      // 优先使用完整地址
      if (item.fullAddress && item.fullAddress !== "地址信息暂无") {
        return item.fullAddress;
      }

      // 构建地址信息
      let addressParts = [];

      // 添加省份信息（如果存在且不等于城市）
      if (item.province && item.province !== item.city) {
        addressParts.push(item.province);
      }

      // 添加城市信息（如果存在且不等于区域）
      if (item.city && item.city !== item.district) {
        addressParts.push(item.city);
      }

      // 添加区域信息
      if (item.district) {
        addressParts.push(item.district);
      }

      // 添加详细地址
      if (item.address) {
        addressParts.push(item.address);
      }

      // 组合地址信息
      if (addressParts.length > 0) {
        return addressParts.join("");
      }

      return "地址信息暂无";
    };

    return {
      map,
      searchKeyword,
      searchResults,
      showSearchResults,
      selectedLocation,
      goBack,
      onSearchInput,
      onSearchFocus,
      onSearchBlur,
      onSearchClick,
      selectLocation,
      confirmLocation,
      showLocationInfo, // 暴露给模板
      toggleLocationInfo, // 暴露给模板
      showError, // 暴露给模板
      retryLoad, // 暴露给模板
      searchHistory, // 暴露给模板
      showSearchHistory, // 暴露给模板
      deleteHistoryItem, // 暴露给模板
      clearAllHistory, // 暴露给模板
      selectHistoryItem, // 暴露给模板
      hideSearchHistory, // 暴露给模板
      handlePageClick, // 暴露给模板
      handleErrorPageClick, // 暴露给模板
      getDisplayAddress, // 暴露给模板
      getDetailedAddress, // 暴露给模板
    };
  },
};
</script>

<style lang="scss" scoped>
/* 全局禁止滚动样式 */
:deep(html),
:deep(body) {
  overflow: hidden !important;
  overscroll-behavior: none !important;
  -webkit-overflow-scrolling: auto !important;
  touch-action: none !important;
  position: fixed !important;
  width: 100% !important;
  height: 100% !important;
}

/* 禁止所有滚动容器 */
:deep(*) {
  overscroll-behavior: none;
  -webkit-overflow-scrolling: auto;
}

.map-page {
  width: 100%;
  height: 100vh;
  background-color: #f5f5f5;
  position: relative;
  overflow: hidden;
  /* 处理移动端安全区域 */
  padding-bottom: env(safe-area-inset-bottom, 0px);
  /* 禁止页面滚动和翻页 */
  overscroll-behavior: none;
  -webkit-overflow-scrolling: auto;
  touch-action: none;
  /* 禁止选择文本 */
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  /* 禁止双击缩放 */
  -webkit-touch-callout: none;
  -webkit-tap-highlight-color: transparent;
}

/* 搜索框样式 */
.search-container {
  position: absolute;
  top: 70px;
  left: 0;
  right: 0;
  z-index: 1000;
  background: transparent;
  padding: 10px 15px;
}

.search-box {
  position: relative;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 25px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.15);
  overflow: hidden;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.3);
}

.search-input {
  width: 100%;
  height: 50px;
  padding: 0 50px 0 20px;
  border: none;
  outline: none;
  font-size: 16px;
  background: transparent;
  color: #333;
  font-weight: 500;

  &::placeholder {
    color: #999;
    font-weight: 400;
  }
}

.search-icon {
  position: absolute;
  right: 15px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 18px;
  color: #666;
  transition: all 0.3s ease;

  &:hover {
    color: #333;
    transform: translateY(-50%) scale(1.1);
  }
}

/* 搜索结果列表 */
.search-results {
  margin-top: 10px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
  max-height: 300px;
  overflow-y: auto;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  /* 允许搜索结果列表滚动，但禁止翻页 */
  overscroll-behavior: contain;
  -webkit-overflow-scrolling: touch;
  touch-action: pan-y;
  /* 防止滚动影响页面 */
  scroll-behavior: smooth;
}

.result-item {
  padding: 15px 20px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
  cursor: pointer;
  transition: all 0.3s ease;

  &:last-child {
    border-bottom: none;
  }

  &:hover {
    background-color: rgba(0, 0, 0, 0.05);
    transform: translateX(5px);
  }

  &:active {
    background-color: rgba(0, 0, 0, 0.1);
    transform: translateX(3px);
  }
}

.result-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 5px;
  transition: color 0.3s ease;
}

.result-item:hover .result-title {
  color: #333;
}

.result-address {
  font-size: 14px;
  color: #666;
  line-height: 1.4;
}

/* 搜索历史样式 */
.search-history {
  margin-top: 10px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
  max-height: 400px;
  overflow: hidden;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.3);
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

.history-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.clear-all-btn {
  font-size: 14px;
  color: #ff4444;
  cursor: pointer;
  transition: all 0.3s ease;

  &:hover {
    color: #ff6666;
    transform: scale(1.05);
  }

  &:active {
    transform: scale(0.95);
  }
}

.history-list {
  max-height: 300px;
  overflow-y: auto;
  /* 允许搜索历史列表滚动，但禁止翻页 */
  overscroll-behavior: contain;
  -webkit-overflow-scrolling: touch;
  touch-action: pan-y;
  /* 防止滚动影响页面 */
  scroll-behavior: smooth;
}

.history-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 20px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
  cursor: pointer;
  transition: all 0.3s ease;

  &:last-child {
    border-bottom: none;
  }

  &:hover {
    background-color: rgba(0, 0, 0, 0.05);
    transform: translateX(5px);
  }

  &:active {
    background-color: rgba(0, 0, 0, 0.1);
    transform: translateX(3px);
  }
}

.history-content {
  display: flex;
  align-items: center;
  flex-grow: 1;
  min-width: 0;
}

.history-icon {
  font-size: 16px;
  margin-right: 10px;
  color: #666;
}

.history-text {
  font-size: 14px;
  color: #333;
  flex-grow: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.history-meta {
  display: flex;
  align-items: center;
  gap: 10px;
}

.history-time {
  font-size: 12px;
  color: #999;
}

.delete-btn {
  font-size: 18px;
  color: #999;
  cursor: pointer;
  padding: 5px;
  border-radius: 50%;
  transition: all 0.3s ease;
  margin-left: 10px;

  &:hover {
    color: #ff4444;
    background-color: rgba(255, 68, 68, 0.1);
    transform: scale(1.2);
  }

  &:active {
    transform: scale(0.9);
  }
}

/* 地图容器 */
#container {
  width: 100%;
  height: calc(100vh - 60px - 60px - env(safe-area-inset-bottom, 0px));
  // margin-top: 60px;
  position: relative;
  /* 禁止地图容器滚动 */
  overflow: hidden;
  overscroll-behavior: none;
  -webkit-overflow-scrolling: auto;
  touch-action: manipulation;
}

/* 位置信息面板 */
.location-info {
  position: absolute;
  bottom: calc(60px + env(safe-area-inset-bottom, 0px));
  left: 0;
  right: 0;
  background: #fff;
  padding: 20px;
  border-radius: 20px 20px 0 0;
  box-shadow: 0 -4px 15px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1); /* 更流畅的动画 */
  transform: translateY(100%); /* 默认收起 */
  max-height: 200px; /* 限制最大高度 */
  /* 禁止面板滚动 */
  overscroll-behavior: none;
  -webkit-overflow-scrolling: auto;
  touch-action: manipulation;

  &--expanded {
    transform: translateY(0); /* 展开时 */
    max-height: 300px; /* 展开时的最大高度 */
  }
}

.location-info-collapsed {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px 0;
  cursor: pointer;
  transition: all 0.3s ease;
  border-radius: 20px 20px 0 0;
  background: linear-gradient(
    135deg,
    rgba(255, 255, 255, 0.95) 0%,
    rgba(255, 255, 255, 0.9) 100%
  );
  backdrop-filter: blur(10px);

  &:hover {
    background: linear-gradient(
      135deg,
      rgba(255, 255, 255, 1) 0%,
      rgba(255, 255, 255, 0.95) 100%
    );
    transform: translateY(-2px);
    box-shadow: 0 -6px 20px rgba(0, 0, 0, 0.15);
  }

  &:active {
    transform: translateY(0);
  }
}

.location-title-collapsed {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-right: 10px;
  flex-grow: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.expand-icon {
  font-size: 18px;
  color: #666;
  transition: transform 0.3s ease;

  &:hover {
    color: #333;
    transform: translateY(-2px);
  }
}

.location-info-expanded {
  padding-top: 15px;
  animation: slideIn 0.4s cubic-bezier(0.4, 0, 0.2, 1);
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.location-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
}

.location-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.collapse-icon {
  font-size: 18px;
  color: #666;
  cursor: pointer;
  transition: transform 0.3s ease;

  &:hover {
    color: #333;
    transform: translateY(-2px);
  }
}

.location-address {
  font-size: 14px;
  color: #666;
  line-height: 1.4;
  margin-bottom: 20px;
}

.confirm-btn {
  width: 100%;
  height: 50px;
  background: linear-gradient(135deg, #ff4444 0%, #ff6666 100%);
  color: #fff;
  border: none;
  border-radius: 25px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  /* 确保按钮文字垂直居中 */
  display: flex;
  align-items: center;
  justify-content: center;
  line-height: 1;

  &:active {
    transform: translateY(1px);
    box-shadow: 0 2px 8px rgba(255, 68, 68, 0.3);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-container {
    top: 60px;
    padding: 8px 10px;
  }

  .search-input {
    height: 45px;
    font-size: 15px;
  }

  #container {
    height: calc(100vh - 50px - 60px - env(safe-area-inset-bottom, 0px));
    // margin-top: 50px;
  }

  .location-info {
    padding: 15px;
    bottom: calc(60px + env(safe-area-inset-bottom, 0px));

    &--expanded {
      max-height: 250px; /* 移动端展开时的最大高度 */
    }
  }

  .location-info-collapsed {
    padding: 12px 0;
  }

  .location-title-collapsed {
    font-size: 15px;
  }

  .search-history {
    max-height: 350px;
  }

  .history-list {
    max-height: 250px;
  }

  .history-item {
    padding: 10px 15px;
  }

  .history-text {
    font-size: 13px;
  }

  .history-time {
    font-size: 11px;
  }

  .delete-btn {
    font-size: 16px;
    padding: 3px;
  }

  .confirm-btn {
    height: 45px;
    font-size: 15px;
    /* 确保移动端按钮文字也垂直居中 */
    display: flex;
    align-items: center;
    justify-content: center;
    line-height: 1;
  }
}

/* 空历史记录样式 */
.empty-history {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  color: #999;
}

.empty-icon {
  font-size: 40px;
  margin-bottom: 10px;
}

.empty-text {
  font-size: 14px;
  color: #999;
}

/* 错误页面样式 */
.error-container {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
}

.error-content {
  text-align: center;
  padding: 40px 20px;
}

.error-icon {
  font-size: 60px;
  margin-bottom: 20px;
}

.error-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 10px;
}

.error-message {
  font-size: 14px;
  color: #666;
  margin-bottom: 30px;
}

.retry-btn {
  background: linear-gradient(135deg, #007aff 0%, #0056cc 100%);
  color: #fff;
  border: none;
  border-radius: 25px;
  padding: 12px 30px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.retry-btn:active {
  transform: translateY(1px);
  box-shadow: 0 2px 8px rgba(0, 122, 255, 0.3);
}
</style>